package com.bdqn.qnnews.search.service.impl;

import com.bdqn.qnnews.articel.api.dto.ApArticleDto;
import com.bdqn.qnnews.articel.api.feign.ArticleFeignClient;
import com.bdqn.qnnews.common.base.R;
import com.bdqn.qnnews.search.convert.AppInfoArticleConvert;
import com.bdqn.qnnews.search.entity.AppInfoArticle;
import com.bdqn.qnnews.search.service.EsDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 * @author xlzhang
 * @date 2024/1/9 10:41
 */
@RequiredArgsConstructor
@Service
public class EsDataServiceImpl implements EsDataService {
    // 远程从文章微服务查询所有的文章列表数据
    private final ArticleFeignClient articleFeignClient;
    // es的操作工具对象
    private final ElasticsearchRestTemplate esRestTemplate;


    @Override
    public boolean dataInit() {
        // 1. 先创建索引库
        createEsIndex();

        // 2. 再同步数据
        final R<List<ApArticleDto>> allArticleDtos = articleFeignClient.findAllArticles();
        // 将dto转换为AppInfoArticle类型
        final HashSet<AppInfoArticle> appInfoArticles = new HashSet<>();
        for (ApArticleDto articleDto : allArticleDtos.getData()) {
            appInfoArticles.add(AppInfoArticleConvert.INSTANCE.dtoToEntity(articleDto));
        }
        // 将转换后的数据保存es索引库中
        esRestTemplate.save(appInfoArticles);
        return true;
    }

    /**
     * 初始化索引库
     */
    private void createEsIndex() {
        // 查询当前的索引库
        final IndexOperations indexOperations = esRestTemplate.indexOps(AppInfoArticle.class);
        // 判断当前索引是否存在，如果有就先删除旧的索引
        if (indexOperations.exists()){
            indexOperations.delete();
        }
        // 准备好settings数据
        final HashMap<String, Object> settings = new HashMap<>();
        settings.put("number_of_shards",6);
        settings.put("number_of_replicas",6);

        // 准备好mappings数据
        final Document mapping = indexOperations.createMapping(AppInfoArticle.class);
        // 创建索引库
        indexOperations.create(settings, mapping);
    }
}
